import sys
import serial
import serial.tools.list_ports
import platform#@NOTE:用于判断处于哪个操作系统的库
if platform.system()=="Windows":
    from serial.serialwin32 import Serial
elif platform.system()=="Linux":
    print("[SUDO]:检测当前环境为Linux系统，程序将放弃调用【from serial.serialwin32 import Serial】")

# if sys.platform == 'cli':
#     from serial.serialcli import Serial
# else:
#     import os
#     # chose an implementation, depending on os
#     if os.name == 'nt':  # sys.platform == 'win32':
#         from serial.serialwin32 import Serial
#     elif os.name == 'posix':
#         from serial.serialposix import Serial, PosixPollSerial, VTIMESerial  # noqa
#     elif os.name == 'java':
#         from serial.serialjava import Serial
#     else:
#         raise ImportError("Sorry: no implementation for your platform ('{}') available".format(os.name))


class Serial_Info:
    
    def __init__(self) -> None:
        self.Com_ID=[]
        self.Com_Name=[]
        self.Com_Info={}
        self.Serial=None
        pass
        
    
    def LookSerial(self):
        #@NOTE:读取串口信息存放至信息列表
        self.Com_ID=[]
        self.Com_Name=[]
        self.Com_Info={}
        self.Serial=None
        SerialList = list(serial.tools.list_ports.comports())
        for Com in SerialList:
            self.Com_ID.append(Com[0])
            self.Com_Name.append(Com[1])
            self.Com_Info[Com[1]]=Com[0]
        return self.Com_Name
 
    def OpenSerial(self,SerialInfo,Baud,Stop,Check,Data):
        if platform.system()=="Windows":
            COM_ID=str(self.Com_Info[SerialInfo]).lower()#@NOTE:这个参数必须小写就很有意思
        elif platform.system()=="Linux":
            COM_ID=str(self.Com_Info[SerialInfo])#@NOTE:无需小写，但不知道是否兼容全小写
        try:
            try:
                self.Serial=serial.Serial(COM_ID,Baud,timeout=0.5)#@NOTE:64位
            except:
                self.Serial=Serial(COM_ID,Baud)#@NOTE:32位
        except:
            return False
        self.Serial.parity=Check[0]#@NOTE:校验位为['NONE','EVEN','ODD','MARK','SPACE']的首字母
        self.Serial.bytesize=int(Data)#@NOTE:数据位必须int
        self.Serial.stopbits=int(Stop)#@NOTE:停止位必须int
        return self.Serial
        
    def CloseSerial(self):
        if self.Serial.isOpen()==True:
            self.Serial.close()
            return 1
        else:
            return 0

    def Com_SendMsn(self,MSN):
        self.Serial.write(MSN.encode())

    def Com_Receiv(self):
        try:
            Recive_Buff=self.Serial.read_all()
        except:
            return False
        return Recive_Buff
        
    
        
        
        
    
    

        


